package com.insurance.config.shiro;

import com.insurance.filter.AuthenticationTokenFilter;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * shiro配置
 * @version 1.0
 * @date 2021/2/22
 **/
@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // Shiro的核心安全接口,这个属性是必须的
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
        //过滤链
        Map<String, Filter> filters = new LinkedHashMap<String, Filter>();
        filters.put("authenticationTokenFilter", authenticationTokenFilter());
        shiroFilterFactoryBean.setFilters(filters);

        filterChainDefinitionMap.put("/common/**", "anon");
        filterChainDefinitionMap.put("/authentication/form/login", "anon");
        filterChainDefinitionMap.put("/authentication/getAccessToken", "anon");
        filterChainDefinitionMap.put("/**", "authenticationTokenFilter");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    /**
     * token拦截器
     * @return
     */
    public AuthenticationTokenFilter authenticationTokenFilter(){
        AuthenticationTokenFilter authenticationTokenFilter = new AuthenticationTokenFilter();
        return authenticationTokenFilter;
    }

    /**
     * 安全控制器
     * @return
     */
    @Bean
    public SecurityManager securityManager(){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 设置realm
        securityManager.setRealm(userRealm());
        return securityManager;
    }

    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }


}
